package com.spring.study.simple_reflection;

import com.my.spring.source.simple_reflection.UserController;
import com.my.spring.source.simple_reflection.UserService;
import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author zlx
 * @Description 基于反射 为对象设置属性
 * @Date 2020-07-15
 * @Param
 * @return
 **/
public class MyTest1 {


    //基于发射原理，将userService对象传入UserController
    @Test
    public void testReflection() throws Exception{


        UserController userController = new UserController();

        //创建对象
        UserService userService = new UserService();

        System.out.println(userService);

        Class clazz = userController.getClass();
        //2、获取属性字段
        Field field = clazz.getDeclaredField("userService");

        //field.setAccessible(true);
        String name = field.getName();
        //构建对应属性的set方法
        String setMethodName = "set" + name.substring(0,1).toUpperCase() + name.substring(1);
        System.out.println("methodName is:=====" + setMethodName);
        //通过方法注入属性对象
        Method method = clazz.getMethod(setMethodName, UserService.class);
        //方法调用
        method.invoke(userController, userService);

        UserService service = userController.getUserService();
        //答应可以发现和userService是同一个对象
        System.out.println(service);

    }


}
